﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AntDesign;
using ERP.Abp.AntDesignUI;
using ERP.Abp.AspnetCore.Components.Web.AntDesignTheme.Toolbars;
using ERP.Workflow.Designer.Application.Contracts;
using ERP.Workflow.Designer.BlazorUI;
using ERP.Workflow.Designer.Domain.Shared.Localization;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.AspNetCore.Components.Web.Extensibility.EntityActions;
using Volo.Abp.AspNetCore.Components.Web.Extensibility.TableColumns;
using Volo.Abp.Localization;

namespace ERP.Workflow.Designer.BlazorUI.Pages;

public partial class DesignerList:IDisposable
{
    protected const string? PermissionProviderName = "U";
    protected IReadOnlyList<DefinitionDto>? Definitions;
    protected string? ManagePermissionsPolicyName;
    protected bool HasManagePermissionsPermission { get; set; }

    private List<CustTableColumn> DefinitionTableColumns = new List<CustTableColumn>();

 
    public DesignerList()
    {
        LocalizationResource = typeof(WorkflowDesignerResource);
        ObjectMapperContext = typeof(WorkflowDesignerBlazorUIModule);
        UIEventBus.On(EventConst.DesignerList_Refresh, async (sender, args) =>
        {
            await SearchEntitiesAsync();
        });

        //   CreatePolicyName = IdentityPermissions.Users.Create;
        //  UpdatePolicyName = IdentityPermissions.Users.Update;
        //  DeletePolicyName = IdentityPermissions.Users.Delete;
        // ManagePermissionsPolicyName = IdentityPermissions.Users.ManagePermissions;
    }
    
    protected override async Task OnInitializedAsync()
    {

          _definitionAppService!.IsExistAsync(Guid.NewGuid());


        await base.OnInitializedAsync();

      
        try
        {
          //  Definitions = (await AppService.GetAssignableRolesAsync()).Items;
        }
        catch (Exception ex)
        {
            await HandleErrorAsync(ex);
        }
    }

    protected override ValueTask SetBreadcrumbItemsAsync()
    {
        BreadcrumbItems.Add(new AbpBreadcrumbItem(L["Menu:IdentityManagement"]));
        BreadcrumbItems.Add(new AbpBreadcrumbItem(L["Users"]));

        return base.SetBreadcrumbItemsAsync();
    }

    protected override async Task SetPermissionsAsync()
    {
        await base.SetPermissionsAsync();

     //   HasManagePermissionsPermission =   await AuthorizationService.IsGrantedAsync(IdentityPermissions.Users.ManagePermissions);
    }

    protected override Task OpenCreateModalAsync()
    {
        NavigationManager.NavigateTo("/workflow/designer/" + Guid.NewGuid().ToString());
        return Task.CompletedTask;
    }

    protected override Task OnCreatingEntityAsync()
    {
        // apply roles before saving
       // NewEntity.RoleNames = NewUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray();

        return base.OnCreatingEntityAsync();
    }

    protected override async Task OpenEditModalAsync(DefinitionDto entity)
    {
        try
        {
           
            await base.OpenEditModalAsync(entity);
        }
        catch (Exception ex)
        {
            await HandleErrorAsync(ex);
        }
    }

    protected override Task OnUpdatingEntityAsync()
    {
        // apply roles before saving
       // EditingEntity.RoleNames = EditUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray();
        return base.OnUpdatingEntityAsync();
    }

    protected override string GetDeleteConfirmationMessage(DefinitionDto entity)
    {
        return string.Format($"是否删除该流程[{entity.Name}]？");
    }

    protected override ValueTask SetEntityActionsAsync()
    {
        EntityActions
            .Get<DesignerList>()
            .AddRange(new EntityAction[]
            {
                    //new EntityAction
                    //{
                    //    Text = L["Permission:Edit"],
                    //    Visible = (data) => HasUpdatePermission,
                    //    Clicked = async (data) => await OpenEditModalAsync(data.As<DefinitionDto>())
                    //},
                    //new EntityAction
                    //{
                    //    Text = L["Permission:ChangePermissions"],
                    //    Visible = (data) => HasManagePermissionsPermission,
                    //    Clicked = async (data) =>
                    //    {
                           
                    //    }
                    //},
                    new EntityAction
                    {
                        Text = L["Delete"],
                        Visible =(data)=>true,// (data) => HasDeletePermission,
                        Clicked = async (data) => await DeleteEntityAsync(data.As<DefinitionDto>()),
                        ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As<DefinitionDto>())
                    }
            });

        return base.SetEntityActionsAsync();
    }

    protected override ValueTask SetTableColumnsAsync()
    {
        DefinitionTableColumns
            .AddRange(new CustTableColumn[]
            {
                    new CustTableColumn
                    {
                        Title = L["WorkflowName"],
                           Sortable = true,
                        Data = nameof(DefinitionDto.Name),
                         Component=typeof(WokflowNameLink),
                    },
                    new CustTableColumn
                    {
                        Title = L["Version"],
                        Sortable = false,
                        Data = nameof(DefinitionDto.Version),
                    },
                   new CustTableColumn
                   {
                    Title = L["Actions"],
                    Actions = EntityActions.Get<DesignerList>()
                   },

            });

        return ValueTask.CompletedTask;
    }

    protected override void Dispose(bool disposing)
    {
        UIEventBus.Off(EventConst.DesignerList_Refresh);
        base.Dispose(disposing);
    }
}

 